import {
  Injectable,
  HttpException,
  HttpStatus,
  UnauthorizedException,
} from '@nestjs/common';
import { UserService } from '../user/user.service';
import { MenuService } from '../menu/menu.service';
import { wxloginUrl,AppID,AppSecret } from '../../utils/index';
import { JwtService } from '@nestjs/jwt';
import axios from 'axios';

@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private menuService: MenuService,
    private jwtService: JwtService,
  ) {}

  /**
   * 微信登录处理
   * @param {string} code - 微信授权码
   * @returns {Promise<{userInfo: any, token: string}>} 包含用户信息和JWT令牌的对象
   * @throws {UnauthorizedException} 当微信授权失败时
   */
  async wxlogin(code: string): Promise<{userInfo: any, token: string}> {
    let params = {
      js_code:code,
      secret: AppSecret,
      appid: AppID,
      grant_type: 'authorization_code'
    }
    const { data: res } = await axios.get(wxloginUrl, { params });
    // console.log(res);
    if (!res || !res.openid) {
      throw new UnauthorizedException('无效的响应数据code');
    }
    
    let user = await this.userService.findwx(res.openid);
    if (!user) {
      user = await this.userService.create(res.openid,code);
    }
    
    const payload = { openid: user.openid, id: user.id, name: user.nickname };
    return {
      userInfo: user,
      token: this.jwtService.sign(payload),
    };
  }

  /**
   * 后台管理系统登录
   * @param {string} username - 用户名
   * @param {string} password - 密码
   * @returns {Promise<{role: any, userInfo: any, token: string}>} 包含权限、用户信息和JWT令牌的对象
   * @throws {HttpException} 当登录信息无效时
   */
  async login(username: string, password: string): Promise<{role: any, userInfo: any, token: string}> {
    if (!username || !password) {
      throw new HttpException('用户名或密码不能为空', HttpStatus.BAD_REQUEST);
    }
    
    const user = await this.userService.findUser({ username });
    if (!user) {
      throw new HttpException('用户不存在', HttpStatus.BAD_REQUEST);
    }
    
    if (user.password !== password) {
      throw new HttpException('密码错误', HttpStatus.BAD_REQUEST);
    }
    
    const menuslist = await this.menuService.findList(user.role);
    const payload = { user };
    
    return {
      role: menuslist,
      userInfo: user,
      token: this.jwtService.sign(payload),
    };
  }
}
